package org.atlantis.netty.telnet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

public class TelnetClient {

	public static void main(String[] args) throws IOException {
		ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
				Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
		bootstrap.setPipelineFactory(new TelnetClientPipelineFactory());
		ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8081));
		// 等到连接上服务器，或者连接出现异常
		Channel channel = future.awaitUninterruptibly().getChannel();
		if (!future.isSuccess()) {
			future.getCause().printStackTrace();
			bootstrap.releaseExternalResources();
			return;
		}
		System.out.println(String.format("Connected! Channel is '%s'.", channel.getClass()));
		// 从命令窗口读取数据
		ChannelFuture lastWriteFuture = null;
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			String line = in.readLine();
			if (line == null) break;
			lastWriteFuture = channel.write(line + "\r\n");
			// 如果输入exit，那么等待服务器关闭这个连接
			if (line.toLowerCase().equals("exit")) {
				channel.getCloseFuture().awaitUninterruptibly();
				break;
			}
		}
		// 在关闭前等待所有的消息都从Channel中发送出去了
		if (lastWriteFuture != null) lastWriteFuture.awaitUninterruptibly();
		channel.close().awaitUninterruptibly();
		// 关闭线程池，然后退出
		bootstrap.releaseExternalResources();
	}
}
